package ca.kooki.codesnippet.views;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import ca.kooki.codesnippet.Activator;
import ca.kooki.codesnippet.core.ActionResponse;
import ca.kooki.codesnippet.core.User;

public class NewUserViewHandler implements KeyListener {

  //```````````````````````
  // MEMBER VARIABLES
  //```````````````````````

  public Button buttonAdd;
  public Text inputName;
  public Label labelMessage;
  
  //```````````````````````
  // CONSTRUCTOR
  //```````````````````````
  
  public NewUserViewHandler(Button buttonAdd, Text inputName, Label labelMessage)
  {
    this.buttonAdd = buttonAdd;
    this.inputName = inputName;
    this.labelMessage = labelMessage;
    
    keyReleased(null);
  }
  
  //```````````````````````
  // INTERFACE
  //```````````````````````

  public void keyPressed(KeyEvent e) {
  }

  public void keyReleased(KeyEvent e) {
    buttonAdd.setEnabled(canAddUser());
    if (e != null && (e.keyCode == SWT.KEYPAD_CR || e.keyCode == SWT.CR))
    {
      addNewUser();
    }    
  }
  
  public void addNewUser() 
  {
    String name = inputName.getText().trim();
    User user = new User(name);
    ActionResponse response = Activator.getDefault().getRepository().addUser(user);
    
    if (response.isValid())
    {
      keyReleased(null);
    }
    
    labelMessage.setText(response.getMessage());
  }
    
  //```````````````````````
  // PRIVATE METHODS
  //```````````````````````
  
  private boolean canAddUser()
  {
    String newText = null;

    newText = inputName.getText().trim();
    if (newText.equals(""))
    {
      return false;
    }

    return true;
  }
   
}
